/*****************************************************************************
 * Copyright (C) Marcelo F. Ochoa. All rights reserved.                      *
 * ------------------------------------------------------------------------- *
 * This software is published under the terms of the Apache Software License *
 * version 1.1, a copy of which has been included  with this distribution in *
 * the LICENSE file.                                                         *
 *****************************************************************************/

package com.prism.toolkit;

import java.sql.*;

import java.util.*;
import java.text.*;

/*
 * Upload/Download functionality for Oracle Lite
 */

public class JwpgDocLoad {
  private static oracle.lite.poljdbc.BLOB blobLocator = null;
  private static oracle.lite.poljdbc.CLOB clobLocator = null;
  private static String fileName = null;
  private static boolean cachingContent = false;
/*
 * This should be called from within a document download procedure
 * to signal the DB Prism Gateway that filename is to be downloaded
 * from the document table to the client's browser.
 * Normally, a document will be downloaded to the browser unless the
 * browser sends an 'If-Modified-Since' header to the gateway indicating
 * that it has the requested document in its cache.  In that case,
 * the gateway will determine if the browser's cached copy is up to date,
 * and if it is, it will send a 302 message to the browser indicating
 * that the browser should display the cached copy.  However, because
 * a document URL and a document do not necessarily have a one-to-one
 * relationship in the DB Prism Web Gateway, in some cases it may be
 * undesirable to have the cached copy of a document displayed.  In those
 * cases, the p_bcaching parameter should be set to TRUE to indicate to
 * the gateway to ignore the 'If-Modified-Since' header, and download the
 * document.
 * PARAMS:
 *    filename  : file to download from the document table.
 *    caching   : browser caching enabled?
 */
  public static void DOWNLOADFILE(String filename, boolean caching) {
    fileName = filename;
    cachingContent = caching;
    blobLocator = null;
    clobLocator = null;
  }

  public static void DOWNLOADFILE(String filename) {
    DOWNLOADFILE(filename,true);
  }

  public static void DOWNLOADFILE(oracle.lite.poljdbc.BLOB locator) {
    fileName = null;
    cachingContent = true;
    blobLocator = locator;
    clobLocator = null;
  }

  public static void DOWNLOADFILE(oracle.lite.poljdbc.CLOB locator) {
    fileName = null;
    cachingContent = true;
    clobLocator = locator;
    blobLocator = null;
  }

	public static int ISFILEDOWNLOAD() {
		if (fileName != null || blobLocator != null || clobLocator!= null)
      return 1;
    else
      return 0;
	}

/*
 * Private file upload/download procedures and functions
 *
 * **WARNING**
 * The following procedures are used internally by the
 * DB Prism Gateway.  Do not call them from your Java code.
 *
 *   Get the name of the file to be downloaded
 * RETURNS:
 *  docInfo       encoded document information
 * B - Blob
 * nnXfilename
 * 12XNOT_MODIFIED, if not reload required
 * Error: msg, if there are errors
 */
 public static String GETDOWNLOADFILE(Connection sqlconn) {
   String docTable = null;
   java.util.Date lastClientMod = null;
   try {
    ResultSet rset = null;
    Statement stmt = null;
    try {
      docTable = Jowa.GETCGIVAR("DOCUMENT_TABLE");
      if (docTable==null)
        return "Error: can't get CGI var DOCUMENT_TABLE";
    } catch (Exception e) {
        return "Error: can't get CGI var DOCUMENT_TABLE";
    }
    if (fileName!=null) {
      String lastMod = Jowa.GETCGIVAR("HTTP_IF_MODIFIED_SINCE");
	    // Convert the Date especification to Age format of Servlets Cookie
	    // Acording to non deprected api of JDK 1.1
      if (cachingContent && lastMod!=null) {
        try {
          DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", java.util.Locale.US);
	        lastClientMod = df.parse(lastMod);
        } catch (Exception e) {
          return "Error: can't parse If-Modified-Since header '"+lastMod+"'\n"+e.getMessage();
        }
        try {
          // Create a Statement
          stmt = sqlconn.createStatement();
          // Select the lobs
          rset = stmt.executeQuery("select last_updated from "+docTable+" where name = '"+fileName+"'");
          if (rset.next()) {
            java.sql.Date lastDbMod = rset.getDate(1);
            rset.close();
            stmt.close();
            // Round date to second before comparing
            if ((lastDbMod.getTime()/1000*1000)==(lastClientMod.getTime()/1000*1000))
  		        return fileName.length()+"X"+fileName+"12XNOT_MODIFIED";
          }
        } catch (Exception e) {
          return "Error: can't get last_updated from table '"+docTable+"'\n"+e.getMessage();
        }
      }
		  return fileName.length()+"X"+fileName;
    } else if (blobLocator != null)
        return "B";
      else
        return "C";
   } catch (Exception e) {
      return "Error: internal error:\n"+e.getMessage();
   }
 }

/*
 *   Get the blob to be downloaded
 * RETURNS:
 *  p_blob     blob to be downloaded
 *
 */
 public static oracle.lite.poljdbc.BLOB GETDOWNLOADBLOB() {
    return blobLocator;
 }

/*
 *   Get the clob to be downloaded
 * RETURNS:
 *  p_clob     clob to be downloaded
 *
 */
 public static oracle.lite.poljdbc.CLOB GETDOWNLOADCLOB() {
    return clobLocator;
 }

/*
 * Return the length of a lob to be downloaded.  This is only called
 * when the user hasn't already specified a predetermined content-length.
 * RETURN:
 *   lob length
 *
 */
 public static long GETCONTENTLENGTH() {
    try {
      if (blobLocator != null)
        return blobLocator.length();
      else
        return clobLocator.length();
    } catch (Exception e) {
      return 0;
    }
 }
}
